import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Card, Spin, Table, Popconfirm, Switch} from 'antd';
import routes from './routes';
import {FORM_OPTIONS, PAGE, TABLE, FIXED_COLUMN_WIDTH, DATE_FORMAT} from '../constants';
import {conventEnumValueToString, formatDateTime} from '../utils';
import {PERMISSION} from './constants';
import TextInput from 'Shared/components/TextInput';
import styles from './style.css';
import Return from '../common/Return';
import {SOCSeverity, SOCQLevel, faultType, orderType} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import {newOrderValidator} from './validator';
import {uniqBy} from 'lodash';
const FormItem = Form.Item;

const showDeletedLayout = {
    labelCol: {
        span: 16
    },
    wrapperCol: {
        span: 8
    }
};
const qLevelList = SOCQLevel.toList();
const severityList = SOCSeverity.toList();
export class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showDeleted: false,
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleFilterChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, value);
    };

    onSubmit = () => {
        const isValid = newOrderValidator(this.props.conditions);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true
        });
        this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    onDeleteAll = () => {
        const {details = []} = this.props.conditions;
        const newDetails = details.map(v => Object.assign({}, v, {
            isDelete: !v.isDelete
        }));
        this.props.onUpdateDetail(newDetails);
    };
    onClickDelete = e => {
        const {id} = e.target.dataset;
        const {details = []} = this.props.conditions;
        const newDetails = details.map(v => {
            if(v.id === id)
                return Object.assign({}, v, {
                    isDelete: !v.isDelete
                });
            return v;
        });
        this.props.onUpdateDetail(newDetails);
    };
    onToggleShowDeleted= checked => {
        this.setState({
            showDeleted: checked
        });
    }
    render() {
        const {validate} = this.state;
        const {conditions} = this.props;
        const {details = []} = this.props.conditions;
        const dataSource = details.filter(item => this.state.showDeleted || !item.isDelete);
        const coefficients = ((conditions.complaints || 0) * 0.5) +
                            (conditions.rescues || 0) +
                            ((conditions.compensations || 0) * 2) +
                            ((conditions.returneds || 0) * 5);
        let marketImpact = 0;
        if(coefficients <= 1)
            marketImpact = 1;
        if(coefficients > 1 && coefficients < 10)
            marketImpact = coefficients;
        if(coefficients > 10)
            marketImpact = 10;
        const vehicles = uniqBy(dataSource, 'vin').length;
        const frequency = vehicles / conditions.frequency;
        const soc = (conventEnumValueToString(SOCSeverity, conditions.severity) || 0) * frequency * marketImpact;
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'newPanel.column.repairCode',
                    defaultMessage: '申请单号'
                }),
                dataIndex: 'repairCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'newPanel.column.vin',
                    defaultMessage: 'VIN'
                }),
                dataIndex: 'vin'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'newPanel.column.engineCode',
                    defaultMessage: '发动机号'
                }),
                dataIndex: 'engineCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'newPanel.column.engineModelTransmissionModel',
                    defaultMessage: '变速箱号'
                }),
                dataIndex: 'engineModelTransmissionModel'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'newPanel.column.saleDate',
                    defaultMessage: '销售日期'
                }),
                dataIndex: 'saleDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'newPanel.column.mileage',
                    defaultMessage: '行驶里程'
                }),
                dataIndex: 'mileage'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'newPanel.column.faultType',
                    defaultMessage: '故障类型'
                }),
                dataIndex: 'faultType',
                render: text => conventEnumValueToString(faultType, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.orderType',
                    defaultMessage: '单据类型'
                }),
                dataIndex: 'orderType',
                render: text => conventEnumValueToString(orderType, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'newPanel.materials.clearBtn',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                width: FIXED_COLUMN_WIDTH,
                render: (text, record) => ({
                    children: <a onClick={this.onClickDelete} data-id={record.id}>
                        {this.state.showDeleted && record.isDelete
                            ? this.props.intl.formatMessage({
                                id: 'add.rollback',
                                defaultMessage: '恢复'
                            })
                            : this.props.intl.formatMessage({
                                id: 'add.delete',
                                defaultMessage: '删除'
                            })}
                    </a>
                })
            }
        ];
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'newPanel.card.title',
                                defaultMessage: '基本信息'
                            })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.sapDeliveryCode',
                                            defaultMessage: '编号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conditions.code}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.title',
                                            defaultMessage: '标题'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conditions.title}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.brandCode',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conditions.brandCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.dealerCode',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conditions.dealerCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.productCategoryCode',
                                            defaultMessage: '车型'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conditions.productCategoryCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.serialNumber',
                                            defaultMessage: '公告号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conditions.serialNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.partCode',
                                            defaultMessage: '零件号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conditions.partCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.partName',
                                            defaultMessage: '零件名称'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conditions.partName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.lv1ProductCateCode',
                                            defaultMessage: '一级部件码'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conditions.lv1ProductCateCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.lv2ProductCateCode',
                                            defaultMessage: '二级部件码'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conditions.lv2ProductCateCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.lv3ProductCateCode',
                                            defaultMessage: '三级部件码'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conditions.lv3ProductCateCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.lv1FaultItemCode',
                                            defaultMessage: '故障代码一级'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conditions.lv1FaultItemCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.lv2FaultItemCode',
                                            defaultMessage: '故障代码二级'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conditions.lv2FaultItemCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.lv3FaultItemCode',
                                            defaultMessage: '故障代码三级'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conditions.lv3FaultItemCode}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'newPanel.card.titleSOC',
                                defaultMessage: 'SOC信息'
                            })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.qLevel',
                                            defaultMessage: '问题等级'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validate && !this.props.conditions.qLevel ? 'error' : null} required>
                                        <WrappedSelect
                                            allowClear
                                            name="qLevel"
                                            value={this.props.conditions.qLevel}
                                            options={qLevelList}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.complaints',
                                            defaultMessage: '客户抱怨数'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validate && !this.props.conditions.complaints ? 'error' : null} required>
                                        <LocalizeInputNumber
                                            name="complaints"
                                            value={this.props.conditions.complaints}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.rescues',
                                            defaultMessage: '外出救援数'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validate && !this.props.conditions.rescues ? 'error' : null} required>
                                        <LocalizeInputNumber
                                            name="rescues"
                                            value={this.props.conditions.rescues}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.compensations',
                                            defaultMessage: '客户特殊补偿数'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validate && !this.props.conditions.compensations ? 'error' : null} required>
                                        <LocalizeInputNumber
                                            name="compensations"
                                            value={this.props.conditions.compensations}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.returneds',
                                            defaultMessage: '退换车数'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validate && !this.props.conditions.returneds ? 'error' : null} required>
                                        <LocalizeInputNumber
                                            name="returneds"
                                            value={this.props.conditions.returneds}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.coefficients',
                                            defaultMessage: '市场评价系数'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {coefficients}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.warrantys',
                                            defaultMessage: '保修数'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conditions.warrantys}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.vehicles',
                                            defaultMessage: '影响车辆数'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {vehicles}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.severity',
                                            defaultMessage: '严重度'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validate && !this.props.conditions.severity ? 'error' : null} required>
                                        <WrappedSelect
                                            allowClear
                                            name="severity"
                                            value={this.props.conditions.severity}
                                            options={severityList}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.frequency',
                                            defaultMessage: '频度'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {frequency}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.marketImpact',
                                            defaultMessage: '市场影响'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {marketImpact}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.soc',
                                            defaultMessage: 'SOC'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {soc}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'addPanel.operation.professionalMachiner',
                                        defaultMessage: '售后改进工程师'
                                    })} {...FORM_OPTIONS.item} validateStatus={validate && !conditions.professionalMachiner ? 'error' : null} required>
                                        <TextInput
                                            name="professionalMachiner"
                                            value={conditions.professionalMachiner}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'addPanel.operation.machiner',
                                        defaultMessage: '担当工程师'
                                    })} {...FORM_OPTIONS.item} validateStatus={validate && !conditions.machiner ? 'error' : null} required>
                                        <TextInput
                                            name="machiner"
                                            value={conditions.machiner}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'newPanel.details.title',
                                defaultMessage: 'SOC清单'
                            })}
                            extra={!this.state.isRepeat && <FormItem
                                {...showDeletedLayout}
                                label={this.props.intl.formatMessage({
                                    id: 'newPanel.details.showDeleted',
                                    defaultMessage: '显示删除项'
                                })}>
                                <Switch
                                    size="small"
                                    onClick={this.onToggleShowDeleted}
                                    checked={this.state.showDeleted}
                                    checkedChildren={this.props.intl.formatMessage({
                                        id: 'yes',
                                        defaultMessage: '是'
                                    })}
                                    unCheckedChildren={this.props.intl.formatMessage({
                                        id: 'no',
                                        defaultMessage: '否'
                                    })} />
                            </FormItem>}>
                            <Table
                                className="white-space-nowrap"
                                rowKey="id"
                                columns={columns}
                                pagination={false}
                                dataSource={dataSource}
                                {...TABLE} />
                        </Card>
                        {this.props.submitable && (
                            <Card type="inner">
                                <Row>
                                    <Col className="col-align-right">
                                        <Button
                                            key="submit"
                                            type="primary"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}>
                                            {this.props.intl.formatMessage({
                                                id: 'newPanel.btn.submit',
                                                defaultMessage: '保存'
                                            })}
                                        </Button>
                                    </Col>
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
NewPanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    id: PropTypes.string,
    intl: PropTypes.object,
};
import {connect} from 'react-redux';
import {
    saveSubmitCondition,
    clearData,
    tableSearch,
    onClickUpdate,
    getEditInit,
    deleteAllDetail,
    updateDetail
} from './actions';
import {createSelector} from 'reselect';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';

const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);

const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    (state, ownProps) => ownProps.query,
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permissions, id, detail) => {
        const data = permissions.toJS();
        const submitable = data.includes(PERMISSION.update);
        return submitable;
    }
);
const mapStateToProps = (state, ownProps) => ({
    query: ownProps.query,
    submitable: getPermissions(state, ownProps),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    conditions: getSubmitData(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getEditInit(ownProps.id)),
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
    onSubmit: () =>
        dispatch(onClickUpdate()).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
    onDeleteAll: () => dispatch(deleteAllDetail()),
    onUpdateDetail: newDetails => dispatch(updateDetail(newDetails)),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(NewPanel));
